﻿using Furion.CMS.Application.Dto;
using Furion.CMS.Core;
using Furion.CMS.Domain;
using Mapster;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Furion.CMS.Application.Profile
{
    public class UserProfile : IRegister
    {
        public void Register(TypeAdapterConfig config)
        {
            #region UserInfo
            config.ForType<UserInfo, UserSession>();

            config.ForType<UserInfo, UserDto>()
                .Map(dest => dest.Status, src => src.Enable ? "启用" : "停用");

            config.ForType<UserInfo, UserDetailDto>()
                .Inherits<UserInfo, UserDto>()
                //.Map(dest => dest.Account, src => src.Passports.FirstOrDefault(t => t.Type == PassportType.Normal).Account, w => w.Passports.Any())
                .Map(dest => dest.Roles, src => src.Roles.UnionBy(src.Organizations.SelectMany(s => s.Roles), u => u.Id).Select(s => s.Id))
                .Map(dest => dest.Orgs, src => src.Organizations.Select(s => s.Id));

            config.ForType<UserCreateDto, UserInfo>()
                .Ignore(g => g.Roles);

            config.ForType<UserModifyDto, UserInfo>()
                .Ignore(g => g.Roles)
                .Ignore(g => g.Passports);

            #region Account
            config.ForType<UserInfo, AccountSettingsDto>();
            //.Map(dest => dest.Roles, src => src.Roles.UnionBy(src.Organizations.SelectMany(s => s.Roles), u => u.Id).Select(s => s.Name))
            //.Map(dest => dest.Orgs, src => src.Organizations.Select(s => s.Name));
            config.ForType<UserInfo, AccountSecurityDto>()
                .Map(dest => dest.Account, src => src.Passports.FirstOrDefault(a => a.Type == PassportType.Normal).Account, (src) => src.Passports.Any(a => a.Type == PassportType.Normal));

            config.ForType<AccountSettingsModifyDto, UserInfo>();
            #endregion

            #endregion

            #region UserPassport
            config.ForType<UserPassport, UserPassportDto>()
                .Map(dest => dest.TypeName, src => src.Type.GetDescription())
                .Map(dest => dest.TypeCode, src => src.Type);
            #endregion

            #region UserLoginRecord
            config.ForType<UserLoginRecord, LoginRecordDto>()
                    .Map(dest => dest.Result, src => src.IsSuccess ? "成功" : "失败")
                    .Map(dest => dest.Host, src => src.Host.Replace("::1", "0.0.0.1"));

            config.ForType<UserLoginRecord, LoginRecordDetailDto>()
                .Inherits<UserLoginRecord, LoginRecordDto>()
                .Map(dest => dest.HasPassport, src => true, t => t.Passport != null)
                .Map(dest => dest.PassportType, src => src.Passport.Type.GetDescription(), t => t.Passport != null)
                .Map(dest => dest.PassportUser, src => src.Passport.User.Adapt<UserDto>(), t => t.Passport != null);
            #endregion
        }
    }
}
